package com.stenio.fancat.pay;

import com.stenio.fancat.util.StringUtil;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.TreeMap;

public class Md5Encryptor implements Encryptor {

    @Override
    public String encrypt(Object o, String key) {
        TreeMap<String, Object> map = new TreeMap<>();
        for (Method method : o.getClass().getDeclaredMethods()) {
            if (method.getName().startsWith("get")) {
                String k = method.getName().substring(3, 4).toLowerCase() + method.getName().substring(4);
                try {
                    if ("sign".equals(k)) {
                        continue;
                    }
                    Object v = method.invoke(o);
                    if (v != null) {
                        map.put(k, v);
                    }
                } catch (IllegalAccessException e) {
                    // do nothing
                } catch (InvocationTargetException e) {
                    // do nothing
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        map.entrySet().forEach((entry) -> {
            Object value = entry.getValue();
            if (sb.length() != 0) {
                sb.append("&");
            }
            sb.append(entry.getKey());
            sb.append("=");
            sb.append(value);
        });
        sb.append("&");
        sb.append("key=");
        sb.append(key);
        System.out.println(sb);
        return StringUtil.md5(sb.toString()).toUpperCase();
    }
}
